﻿using System;
using System.Collections.Generic;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Tareas.ServiceReference;
using System.Threading.Tasks;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.ApplicationSettings;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
namespace Tareas
{

    public sealed partial class CollectionPage
    {
        public CollectionPage()
        {
            InitializeComponent();
            getProjects();
            BackButton.IsEnabled = false;

            try
            {
                SettingsPane pane = SettingsPane.GetForCurrentView();
                pane.ApplicationCommands.Add(new SettingsCommand(KnownSettingsCommand.About, About));
            }
            catch (Exception)
            {
                //Aqui captura el contenido cuando vuelve de otra ventana
                //TODO: Arreglar en proxima version
            }
            
            //DataTransferManager datatransferManager;
            //datatransferManager = DataTransferManager.GetForCurrentView();
            //datatransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(datatransferManager_DataRequested);
        }

        private void About(IUICommand command)
        {
            Settings.Margin = ThicknessHelper.FromUniformLength(0);
        }

        async void getProjects()
        {
            Loading.Text = "Cargando";
            TaskServiceClient client = new TaskServiceClient();
            try
            {
                this.Items = await client.getProjectsAsync();
                client.CloseAsync();
                Loading.Text = "";
                //ActualizarIcono((this.Items as List<Project>).Count);
                TileUpdateManager.CreateTileUpdaterForApplication().Clear();
                UpdateTileWithText("Hola mundo");
            }
            catch (Exception)
            {
                Loading.Text = "Se ha producido un error";
                //Show a Message dialog
            }
        }


        void UpdateTileWithText(string text)
        {
            // GetTemplateContent returns a Windows.Data.Xml.Dom.XmlDocument object containing
            // the tile XML - see the Advanced Tile SDK sample to preview all of the templates
            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText03);

            // You can use the methods from the XML document to specify all of the
            // required parameters for the badge
            XmlNodeList textElements = tileXml.GetElementsByTagName("text");
            textElements.Item(0).AppendChild(tileXml.CreateTextNode(text));

            tileXml.GetXml();

            // Create a tile notification from the Xml, then create a TileUpdater object to update
            // the tile
            TileNotification tile = new TileNotification(tileXml);

            // If you have other applications in your package, you can specify the AppId of
            // the app to create a BadgeUpdater for that application
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);
        }

        void ActualizarTileDoble(string text)
        {
            // GetTemplateContent returns a Windows.Data.Xml.Dom.XmlDocument object containing
            // the tile XML - see the Advanced Tile SDK sample to preview all of the templates
            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText03);

            // You can use the methods from the XML document to specify all of the
            // required parameters for the badge
            XmlNodeList textElements = tileXml.GetElementsByTagName("text");
            textElements.Item(0).AppendChild(tileXml.CreateTextNode(text));

            // Create a tile notification from the Xml, then create a TileUpdater object to update
            // the tile
            TileNotification tile = new TileNotification(tileXml);

            // If you have other applications in your package, you can specify the AppId of
            // the app to create a BadgeUpdater for that application
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);
        }


        /// <summary>
        /// Actualiza el icono de la aplicación con un número
        /// </summary>
        /// <param name="numero"></param>
        void ActualizarIcono(int numero)
        {
            // Se obtiene desde la plantilla el documento XML que contendrá el XML del icono
            XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);

            // Se edita el XML para agregar los datos deseados, en este caso un número
            XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
            badgeElement.SetAttribute("value", "" + numero.ToString());
            badgeElement.SetAttribute("version", "1");

            // Se crea una notificación desde el XML editado
            BadgeNotification badge = new BadgeNotification(badgeXml);

            // Finalmente, se actualiza el contenido de la aplicación 
            BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
        }

        void datatransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            args.Request.Data.Properties.Title = "Ejemplo de titulo";
            args.Request.Data.Properties.Description = "Ejemplo de descripcion";
            args.Request.Data.SetText("Ejemplo de mucho texto");
        }

        void ItemView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Construct the appropriate destination page and set its context appropriately
            var selectedItem = (sender as Selector).SelectedItem as Project;
            App.ShowTaskDetails(selectedItem);
        }

        private IEnumerable<Object> _items;
        public IEnumerable<Object> Items
        {
            get
            {
                return this._items;
            }

            set
            {
                this._items = value;
                CollectionViewSource.Source = value;
            }
        }

        // View state management for switching among Full, Fill, Snapped, and Portrait states

        private DisplayPropertiesEventHandler _displayHandler;
        private TypedEventHandler<ApplicationLayout, ApplicationLayoutChangedEventArgs> _layoutHandler;

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
            SetCurrentViewState(this);
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            DisplayProperties.OrientationChanged -= _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged -= _layoutHandler;
        }

        private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e)
        {
            SetCurrentViewState(this);
        }

        private void Page_OrientationChanged(object sender)
        {
            SetCurrentViewState(this);
        }

        private void SetCurrentViewState(Control viewStateAwareControl)
        {
            VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
        }

        private String GetViewState()
        {
            var orientation = DisplayProperties.CurrentOrientation;
            if (orientation == DisplayOrientations.Portrait ||
                orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
            var layout = ApplicationLayout.Value;
            if (layout == ApplicationLayoutState.Filled) return "Fill";
            if (layout == ApplicationLayoutState.Snapped) return "Snapped";
            return "Full";
        }

        async void Button_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".txt");
            StorageFile file = await openPicker.PickSingleFileAsync();
        }

        private void LayoutRoot_PointerPressed(object sender, Windows.UI.Xaml.Input.PointerEventArgs e)
        {
            if (Settings.Margin.Right == 0)
            {
                Settings.Margin = ThicknessHelper.FromLengths(0, 0, -346, 0);
            }
        }

    }
}
